import QtQuick 1.1
import com.nokia.meego 1.0
import "Logic.js" as Logic

Page {
    id: pageExportWords

    property int selectedCategoryId: 0
    property string exportFolder: ""

    property variant exportCategiriesId: []

    function setDirExport( pathDir )
    {
        pageExportWords.exportFolder = pathDir
        tfXmlFile.text = pathDir
    }


    tools: ToolBarLayout {
        id: tool_only_back
        opacity: userTheme.opacityToolbar
        ToolIcon {
            id: toolIconBack
            //iconId: "toolbar-back"
            iconSource: "images/toolbar/back.png"
            onClicked: {
                pageStack.pop();
            }
        }
    } //ToolBarLayout

    QNMTitle {
        id: titlePage
        text: qsTr("Export of words")
        image: "images/export.png"
        busy: false
    }

    BackgroundPage { }

    Flickable {
        id: flickArea
        anchors {
            top: titlePage.bottom
            bottom: parent.bottom
            left: parent.left
            right: parent.right
            topMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 5 : 15
            leftMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 40 : 20
            rightMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 40 : 20
            bottomMargin: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? 5 : 15
        }

        flickableDirection: Flickable.VerticalFlick

        width: parent.width
        height: parent.height

        contentWidth: contentFlickArea.width
        contentHeight: contentFlickArea.height
        clip: true

        Column {
            id: contentFlickArea
            width: parent.width
            spacing: 20

            Text {
                text: qsTr("Category")
                font.pixelSize: 30
            }
            MyButton {
                id: categorySelectButton
                iconSource: "images/categories_icon.png"
                text: qsTr("List of categories")
                fontSize: 24
                height: 100
                width: flickArea.width
                onClicked: {
                    //dlgSelectCategory.open()
                    dlgExportWords.open()
                }
            }

            Item {
                height: (screen.orientationString == "Portrait") || (screen.orientationString == "PortraitInverted") ? 20 : 5
                width:flickArea.width
            }

            Text {
                text: qsTr("Choose a directory for the export")
                font.pixelSize: 30
            }
            Row {
                TextField {
                    id: tfXmlFile
                    text: pageExportWords.exportFolder
                    height: 70
                    width: flickArea.width - btBrowse.width
                    anchors.verticalCenter: parent.verticalCenter
                    onTextChanged: {
                        pageExportWords.exportFolder = tfXmlFile.text
                        var res = cppMeeWords.checkDir( tfXmlFile.text )
                        if ( res && (tfXmlFile.text != "") && (tfXmlFile.text != "/") ) {
                            btExport.enabled = true
                        } else {
                            btExport.enabled = false
                        }
                    }
                }
                MyButton {
                    id: btBrowse
                    width: 80
                    height: 70
                    anchors.verticalCenter: parent.verticalCenter
                    iconSource: "images/folder_docs.png"
                    indicator: false
                    isGlow: false
                    onClicked: {
                        Logic.openFile("DirListView.qml")
                    }
                }
            }

            Item {
                height: (screen.orientationString == "Portrait") || (screen.orientationString == "PortraitInverted") ? 20 : 5
                width:flickArea.width
            }

            MyButton {
                id: btExport
                height: 100
                width: flickArea.width
                text: qsTr("Start the export")
                iconSource: "images/export.png"
                onClicked: {
                    createExport()
                }
                enabled: false
            }


        }

    } //Flickable


    /*******************************************************************************/
    function createExport() {
        categorySelectButton.enabled = false
        tfXmlFile.enabled = false
        btBrowse.enabled = false
        btExport.enabled = false

        var bufCategoriesExport = exportCategiriesId
        if( bufCategoriesExport.length == 0 ) {
            /* не выбранны категории */
            showDlgExportSelectCat()
            btExport.enabled = true
        } else {
            var pathExport = tfXmlFile.text
            createXmlByWords( pathExport )
            tfXmlFile.text = ""
        }

        categorySelectButton.enabled = true
        tfXmlFile.enabled = true
        btBrowse.enabled = true
        //btExport.enabled = true //не востанавливаем активность кнопки
     }

    function getAllCategories () {
        titlePage.busy = false
        categorySelectButton.enabled = false
        var db = Logic.getDatabase()

        listModelCategories.clear()

        db.transaction( function(tx) {
                           var res = tx.executeSql( "SELECT id,category FROM categories" )
                           for(var i = 0; i<=res.rows.length-1; i++) {
                               categorySelectButton.enabled = true
                               var _id = res.rows.item(i).id;
                               var nameCategory = res.rows.item(i).category;
                               //var descrCategory = res.rows.item(i).description;
                               listModelCategories.append( { name: nameCategory, category_id: _id } );
                           }
                       }
                    )
        /* установка значение для первого элемента */
        titlePage.busy = false
    }

    function createXmlByWords ( pathExport ) {
        /* считываем индексы выбранных категорий */
        var bufCategoriesExport = exportCategiriesId

        var db = Logic.getDatabase()
        var strXML = ""
        db.transaction ( function(tx) {
                           var sql = "SELECT words.*, c.category FROM words LEFT JOIN categories AS c ON words.category_id == c.id "
                           for(var s=0; s<bufCategoriesExport.length; s++) {
                               if ( s == 0 ) {
                                   sql += " WHERE  category_id = " + bufCategoriesExport[s]
                               } else {
                                   sql += " OR category_id = " + bufCategoriesExport[s]
                               }
                           }
                           console.log( sql )
                           var res = tx.executeSql( sql )
                           strXML = "<meewords>\n"
                           for ( var i = 0; i<=res.rows.length-1; i++ ) {
                               //var id = res.rows.item(i).id;
                               var nameWord = res.rows.item(i).word;
                               var transWord = res.rows.item(i).translation;
                               //var nameCategory = res.rows.item(i).category;
                               //var idCategory = res.rows.item(i).category_id;
                               strXML += "\t<words>\n"
                               strXML += "\t\t<word>" + nameWord + "</word>\n"
                               strXML += "\t\t<translation>" + transWord + "</translation>\n"
                               strXML += "\t</words>\n"
                           }
                           strXML += "</meewords>\n"
                       }
                    )
        //console.log( strXML )
        var today = getToday()
        var file = "meewords_export_" + today + ".xml"
        var resExport = cppMeeWords.exportWords( strXML, pathExport, file ) /* сохраняем через с++ */
        /* обрабатываем результат */
        var txt = ""
        if( resExport === "ok" ) {
            txt = "<b>Export completed successfully<b><br/><br/>file: " + file
            showDlgExport( txt )
        } else {
            txt = "<b>Error:</b> " + resExport
            showDlgExport( txt )
        }
    }

    function getToday() {
        var today = new Date();
        var dt = Qt.formatDateTime(today, "yyMMddhhmmss")
        return dt
    }

    /*******************************************************************************/

    ListModel {
        id: listModelSelectedCategories
    }

    ListModel {
        id: listModelCategories
        Component.onCompleted: {
            getAllCategories()
        }
    }

    MultiSelectionDialog {
        id: dlgExportWords
        titleText: qsTr("Selected categories")
        model: listModelCategories
        acceptButtonText: qsTr("Ok")
        rejectButtonText: qsTr("Cancel")
        //selectedIndexes: appWindow.filterWords_indx

        onAccepted: {
            //appWindow.filterWords_indx = dlgExportWords.selectedIndexes

            var lSel = selectedIndexes.length
            var bufCategoriesExport = new Array()
            listModelSelectedCategories.clear()
            for ( var j=0; j<lSel; j++ ) {
                listModelSelectedCategories.append( { name: dlgExportWords.model.get( dlgExportWords.selectedIndexes[j] ).name } );
                var category_id = dlgExportWords.model.get( dlgExportWords.selectedIndexes[j] ).category_id
                bufCategoriesExport[ bufCategoriesExport.length ] = category_id
                console.log( bufCategoriesExport[ bufCategoriesExport.length-1 ] )
            }
            exportCategiriesId = bufCategoriesExport

            //createXmlByWords()
        }

        /*onRejected: {
            resetFilterWords()
        }*/
    }

    QueryDialog {
        id: dlgExport
        titleText: qsTr("Export")
        icon: "images/export.png"
        onRejected: {
            pageStack.pop()
        }
    }
    function showDlgExport( text ) {
        dlgExport.message = text
        dlgExport.open()
    }

    QueryDialog {
        id: dlgSelectedCategory
        titleText: qsTr("Export")
        message: qsTr("Please, selected categories")
        icon: "images/export.png"
    }
    function showDlgExportSelectCat( ) {
        dlgSelectedCategory.open()
    }

}
